
import * as COS from 'cos-nodejs-sdk-v5';
import * as dayjs from 'dayjs';
import {nanoid} from 'nanoid';
import { getConfig } from './index';

const configService=getConfig().TENCENT_CONFIG;


const cos = new COS({
  SecretId: configService.secretId,
  SecretKey: configService.secretKey,
});

/**
 * 腾讯云上传文件接口
 * @param file 文件
 * @param type 文件类型
 * @param folder 文件夹名称
 * @returns 
 */
export const uploadFile=(file:any,type:string,folder:string)=>{
  let cosBody=file;
  if (type === 'base64') {
    cosBody = Buffer.from(file, 'base64');
  }
  const fileName= dayjs().format('YYYYMMDDHHmmss') + '_' + nanoid(7)

  return new Promise((resolve,reject)=>{
    cos.putObject({
      Bucket:configService.bucket,
      Region:configService.region,
      Key:folder+fileName+'.png',
      StorageClass:'STANDARD',
      Body:cosBody
    },(err,data)=>{
      const res = {
        code: 200,
        data: {},
        msg: '',
      };
      if (err) {
        res.code = 500;
        res.data = {
          err,
        };
        res.msg = '保存数据失败!';
        reject(res);
      }
      const { statusCode, Location } = data;
      if (statusCode === 200) {
        res.data = {
          ImageUrl: Location,
        };
        res.msg='保存数据成功!'
        resolve(res);
      } else {
        res.code = 400;
        res.data = {
          data,
        };
        res.msg='保存数据失败!'
        reject(res);
      }
    })
  })
}
